package com.gm.wj.service;

import com.gm.wj.dao.AdminMenuDAO;
import com.gm.wj.entity.AdminMenu;
import com.gm.wj.entity.AdminRoleMenu;
import com.gm.wj.entity.AdminUserRole;
import com.gm.wj.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @author Evan
 * @date 2019/10
 */
@Slf4j
@Service
public class AdminMenuService {
    @Autowired
    AdminMenuDAO adminMenuDAO;
    @Autowired
    UserService userService;
    @Autowired
    AdminUserRoleService adminUserRoleService;
    @Autowired
    AdminRoleMenuService adminRoleMenuService;

    public List<AdminMenu> getAllByParentId(int parentId) {
        return adminMenuDAO.findAllByParentId(parentId);
    }

    public List<AdminMenu> getMenusByCurrentUser() {
        // Get current user in DB.
        String username = SecurityUtils.getSubject().getPrincipal().toString();
        User user = userService.findByUsername(username);

        // Get roles' ids of current user.
        // 查询得到所有的user数组  再从里面抽出Rid循环给rids
        List<Integer> rids = adminUserRoleService.listAllByUid(user.getId())
                .stream().map(AdminUserRole::getRid).collect(toList());

        // Get menu items of these roles.
        List<Integer> menuIds = adminRoleMenuService.findAllByRid(rids)
                .stream().map(AdminRoleMenu::getMid).collect(toList());
        List<AdminMenu> menus = adminMenuDAO.findAllById(menuIds).stream().distinct().collect(toList());
//        log.info("menus权限列表：" + menus.toString());

        // Adjust the structure of the menu.
        /**
        * static局部变量和普通局部变量有什么区别：static局部变量只被初始化一次，下一次依据上一次结果值；
        * 那对象数组为什么是静态变量 
        */
        handleMenus(menus);
        return menus;
    }

    public List<AdminMenu> getMenusByRoleId(int rid) {  // 角色id
        List<Integer> menuIds = adminRoleMenuService.findAllByRid(rid)  // 根据角色id查找所有的菜单id
                .stream().map(AdminRoleMenu::getMid).collect(toList());
        List<AdminMenu> menus = adminMenuDAO.findAllById(menuIds);  // 根据角色id查找所有的菜单id  菜单id再查出菜单信息
        return handleMenus3(menus);
    }

    public List<AdminMenu> getMenusAll() {
        List<AdminMenu> menus = adminMenuDAO.findAll();
        return handleMenus(menus);
    }

    /**
     * Adjust the Structure of the menu.
     *
     * @param menus Menu items list without structure
     */
    public List<AdminMenu> handleMenus(List<AdminMenu> menus) {
        menus.forEach(m -> {
            // m.getId() ： 父id  children ：查出来的子数据
            List<AdminMenu> children = getAllByParentId(m.getId());  // 我有父id 去查父id下所有的子id 这个查询父id，都查进去了，问题在这   // 101
            List<AdminMenu> children1 = new ArrayList<AdminMenu>();
            for(int i = 0; menus.size()>i; i++){
                if(children.size()>0) {
                    for (int j = 0; children.size() > j; j++) {
                        if (menus.get(i).getId() == children.get(j).getId()) {
                            children1.add(children.get(j));
                            m.setChildren(children1);
                            continue;
                        }
                    }
                }
            }
        });
        menus.removeIf(m -> m.getParentId() != 0);
        return menus;
    }

    /**
     * 树形菜单，跟上面一样的效果
     * @param menus
     * @return
     */
    private List<AdminMenu> handleMenus3(List<AdminMenu> menus) {
        List<AdminMenu> collect = menus.stream().filter(m -> m.getParentId() == 0).peek(m -> {
            m.setChildren(getChildrenList(menus, m.getId()));
        }).collect(toList());
        return collect;
    }

    public List<AdminMenu> getChildrenList(List<AdminMenu> all, int parentId) {
        List<AdminMenu> collect = all.stream().filter(m -> m.getParentId() == parentId).collect(toList());
        return collect;
    }

}
